package client.log;

import client.common.dto.GetOperationLogByPageDto;
import client.common.result.Result;
import client.common.result.emun.ResultCodeEnum;
import client.log.formate.DateLabelFormatter;
import com.alibaba.fastjson2.JSONObject;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;
import org.jdatepicker.impl.JDatePanelImpl;
import remote.service.LogService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class LogView extends JFrame {
    private final LogService logService = new LogService() {
    };
    private JTable dataTable;
    private DefaultTableModel tableModel;
    private GetOperationLogByPageDto dto;
    private Integer currentPage = 1;
    private Integer pageSize = 15;
    private Integer totalPages = 1;
    // Pagination controls
    private JButton firstPageButton;
    private JButton prevPageButton;
    private JButton nextPageButton;
    private JButton lastPageButton;
    private JLabel pageInfoLabel;

    // Filter components
    private JComboBox<String> operationTypeComboBox;

    // Filter components
    private JDatePickerImpl startDatePicker;
    private JDatePickerImpl endDatePicker;

    public LogView() {

        setTitle("操作日志信息查询");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        setLayout(new BorderLayout(10, 10));

        JPanel filterPanel = createFilterPanel();
        add(filterPanel, BorderLayout.NORTH);

        JPanel tablePanel = createTablePanel();
        add(tablePanel, BorderLayout.CENTER);

        JPanel paginationPanel = createPaginationPanel();
        add(paginationPanel, BorderLayout.SOUTH);

        initTable();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            LogView logView = new LogView();
            logView.setVisible(true);
        });
    }

    /**
     * 创建过滤面板
     */
    private JPanel createFilterPanel() {
        JPanel filterPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        // Start Date
        gbc.gridx = 0;
        gbc.gridy = 0;
        filterPanel.add(new JLabel("开始日期:"), gbc);

        UtilDateModel startModel = new UtilDateModel();
        Properties startProperties = new Properties();
        startProperties.put("text.today", "今天");
        startProperties.put("text.month", "月");
        startProperties.put("text.year", "年");
        JDatePanelImpl startPanel = new JDatePanelImpl(startModel, startProperties);
        startDatePicker = new JDatePickerImpl(startPanel, new DateLabelFormatter());
        startDatePicker.addActionListener(e -> {
            if (startModel.getValue() != null) {
                startDatePicker.getJFormattedTextField().setText(
                        new SimpleDateFormat("yyyy-MM-dd").format(startModel.getValue())+" 00:00:00");
            }
        });
        gbc.gridx = 1;
        filterPanel.add(startDatePicker, gbc);

        // End Date
        gbc.gridx = 0;
        gbc.gridy = 1;
        filterPanel.add(new JLabel("结束日期:"), gbc);

        UtilDateModel endModel = new UtilDateModel();
        JDatePanelImpl endPanel = new JDatePanelImpl(endModel, startProperties);
        endDatePicker = new JDatePickerImpl(endPanel, new DateLabelFormatter());
        endDatePicker.addActionListener(e -> {
            if (endModel.getValue() != null) {
                endDatePicker.getJFormattedTextField().setText(
                        new SimpleDateFormat("yyyy-MM-dd").format(endModel.getValue())+" 23:59:59");
            }
        });
        gbc.gridx = 1;
        filterPanel.add(endDatePicker, gbc);

        // Operation Type
        gbc.gridx = 0;
        gbc.gridy = 2;
        filterPanel.add(new JLabel("操作类型:"), gbc);

        operationTypeComboBox = new JComboBox<>(new String[]{"", "PERMISSION", "PERSON", "MATERIALS", "OTHER"});
        gbc.gridx = 1;
        filterPanel.add(operationTypeComboBox, gbc);

        // Search button
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(e -> {
            currentPage = 1;
            freshTable();
        });
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2; // 按钮占用两列
        filterPanel.add(searchButton, gbc);

        return filterPanel;
    }


    /**
     * 创建表格面板
     */
    private JPanel createTablePanel() {
        JPanel tablePanel = new JPanel(new BorderLayout());

        tableModel = new DefaultTableModel(new Object[]{"operationUser", "operation", "description", "type"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        dataTable = new JTable(tableModel);
        dataTable.setFillsViewportHeight(true);
        dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        dataTable.setFont(new Font("Serif", Font.PLAIN, 14));
        dataTable.setRowHeight(25);

        JScrollPane scrollPane = new JScrollPane(dataTable);
        tablePanel.add(scrollPane, BorderLayout.CENTER);

        return tablePanel;
    }

    /**
     * 创建分页面板
     */
    private JPanel createPaginationPanel() {
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));

        firstPageButton = new JButton("首页");
        firstPageButton.addActionListener(e -> {
            if (currentPage != 1) {
                currentPage = 1;
                freshTable();
            }
        });
        paginationPanel.add(firstPageButton);

        prevPageButton = new JButton("上一页");
        prevPageButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                freshTable();
            }
        });
        paginationPanel.add(prevPageButton);

        nextPageButton = new JButton("下一页");
        nextPageButton.addActionListener(e -> {
            if (currentPage < totalPages) {
                currentPage++;
                freshTable();
            }
        });
        paginationPanel.add(nextPageButton);

        lastPageButton = new JButton("末页");
        lastPageButton.addActionListener(e -> {
            if (currentPage != totalPages) {
                currentPage = totalPages;
                freshTable();
            }
        });
        paginationPanel.add(lastPageButton);

        pageInfoLabel = new JLabel("第 1 页 / 共 1 页");
        pageInfoLabel.setFont(new Font("Serif", Font.PLAIN, 14));
        paginationPanel.add(pageInfoLabel);

        return paginationPanel;
    }
    public void initTable(){
        GetOperationLogByPageDto getOperationLogByPageDto = new GetOperationLogByPageDto();
        getOperationLogByPageDto.setCurrentPage(currentPage);
        getOperationLogByPageDto.setSize(pageSize);
        getOperationLogByPageDto.setIsForExport(false);
        // 获取选择的开始日期和结束日期
        String startDate = null;
        String endDate = null;
        // 设置过滤条件
        getOperationLogByPageDto.setStartTime(startDate);
        getOperationLogByPageDto.setEndTime(endDate);
        getOperationLogByPageDto.setType((String) operationTypeComboBox.getSelectedItem());

        Result<Map<String, Object>> result = logService.getOperationLogListByPage(getOperationLogByPageDto);

        if (result == null || result.getCode() == null) {
            JOptionPane.showMessageDialog(this, "获取数据失败", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (result.getCode().equals(ResultCodeEnum.NO_PERMISSION.getCode())) {
            JOptionPane.showMessageDialog(this, "权限不足，请联系管理员", "错误", JOptionPane.ERROR_MESSAGE);
            setVisible(false);
            dispose();
            return;
        }
        setVisible(true);

        Map<String, Object> resultData = result.getData();
        List<JSONObject> logList = (List<JSONObject>) resultData.get("data");
        Integer totalPage = (Integer) resultData.get("totalPage");

        // 更新总页数
        this.totalPages = totalPage != null ? totalPage : 1;
        pageInfoLabel.setText("第 " + currentPage + " 页 / 共 " + totalPages + " 页");

        // 控制分页按钮的启用状态
        firstPageButton.setEnabled(currentPage > 1);
        prevPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);

        // 清空表格
        tableModel.setRowCount(0);

        // 显示日志数据
        if (logList != null && !logList.isEmpty()) {
            for (JSONObject log : logList) {
                tableModel.addRow(new Object[]{
                        log.getString("operationUser"),
                        log.getString("operationTime"),
                        log.getString("description"),
                        log.getString("type"),
                });
            }
        } else {
            // 如果没有数据，更新分页信息
            pageInfoLabel.setText("第 " + currentPage + " 页 / 共 0 页");
            firstPageButton.setEnabled(false);
            prevPageButton.setEnabled(false);
            nextPageButton.setEnabled(false);
            lastPageButton.setEnabled(false);
        }
    }

    /**
     * 重新请求接口，刷新表单
     */
    public void freshTable() {
        GetOperationLogByPageDto getOperationLogByPageDto = new GetOperationLogByPageDto();
        getOperationLogByPageDto.setCurrentPage(currentPage);
        getOperationLogByPageDto.setSize(pageSize);
        getOperationLogByPageDto.setIsForExport(false);
        // 获取选择的开始日期和结束日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // Customize the format as needed
        String startDate = startDatePicker.getModel().getValue() != null
                ? dateFormat.format(startDatePicker.getModel().getValue())+" 00:00:00"
                : null;
        String endDate = endDatePicker.getModel().getValue() != null
                ? dateFormat.format(endDatePicker.getModel().getValue())+" 23:59:59"
                : null;
        // 设置过滤条件
        getOperationLogByPageDto.setStartTime(startDate);
        getOperationLogByPageDto.setEndTime(endDate);
        getOperationLogByPageDto.setType((String) operationTypeComboBox.getSelectedItem());

        Result<Map<String, Object>> result = logService.getOperationLogListByPage(getOperationLogByPageDto);

        if (result == null || result.getCode() == null) {
            JOptionPane.showMessageDialog(this, "获取数据失败", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (result.getCode().equals(ResultCodeEnum.NO_PERMISSION.getCode())) {
            JOptionPane.showMessageDialog(this, "权限不足，请联系管理员", "错误", JOptionPane.ERROR_MESSAGE);
            setVisible(false);
            dispose();
            return;
        }
        setVisible(true);

        Map<String, Object> resultData = result.getData();
        List<JSONObject> logList = (List<JSONObject>) resultData.get("data");
        Integer totalPage = (Integer) resultData.get("totalPage");

        // 更新总页数
        this.totalPages = totalPage != null ? totalPage : 1;
        pageInfoLabel.setText("第 " + currentPage + " 页 / 共 " + totalPages + " 页");

        // 控制分页按钮的启用状态
        firstPageButton.setEnabled(currentPage > 1);
        prevPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);

        // 清空表格
        tableModel.setRowCount(0);

        // 显示日志数据
        if (logList != null && !logList.isEmpty()) {
            for (JSONObject log : logList) {
                tableModel.addRow(new Object[]{
                        log.getString("operationUser"),
                        log.getString("operationTime"),
                        log.getString("description"),
                        log.getString("type"),
                });
            }
        } else {
            // 如果没有数据，更新分页信息
            pageInfoLabel.setText("第 " + currentPage + " 页 / 共 0 页");
            firstPageButton.setEnabled(false);
            prevPageButton.setEnabled(false);
            nextPageButton.setEnabled(false);
            lastPageButton.setEnabled(false);
        }
    }

}